<?php
/**
 * @package PWE.modele.menu
 * @author Gmax <gmaxfr78@gmail.com>
 */
class modele_menu_item extends modele{
    protected static $_table = 'menu_item';
    private $_id;
    private $_menu_id;
    private $_label;
    private $_title;
    private $_link;
    private $_modele;
    private $_modele_id;
    private $_target;
    private $_order;
    private $_class;
    private $_menu_item_id;
    private $_parent = null;
    private $_items = array();
    
    public $type = 'menu_item';
    
    function __construct($id=null){
        if($id!=null){
            $this->_id = $id;
            $this->_constructObject();
        }
    }
    
    private function _constructObject(){
        $sqlQuery = 'SELECT ';
        $sqlQuery .= 't.* ';
        $sqlQuery .= 'FROM '.self::getTable().' as t ';
        $sqlQuery .= 'WHERE t.id='.$this->_id.' ';
        $sqlQuery .= 'LIMIT 1';
        
        $datas = $this->_getOneResult($sqlQuery);
        if($datas){
            $this->_id = $datas['id'];
            $this->_menu_id =  $datas['menu_id'];
            $this->_menu_item_id =  $datas['menu_item_id'];
            $this->_label =  $datas['label'];
            $this->_title =  $datas['title'];
            $this->_link =  $datas['link'];
            $this->_modele =  $datas['modele'];
            $this->_modele_id =  $datas['modele_id'];
            $this->_target =  $datas['target'];
            $this->_order =  $datas['order'];
            $this->_class =  $datas['class'];
        }
    }
    
    public function getId(){
        return $this->_id;
    }
    public function getMenuId(){
        return $this->_menu_id;
    }
    public function getParentId(){
        return ($this->_menu_item_id>0)?$this->_menu_item_id:'NULL';
    }
    
    public function getParent(){
        if($this->_parent===null){
            $this->_parent = ($this->_menu_item_id>0)?new modele_menu_item($this->_menu_item_id):null;
        }
        return $this->_parent;
    }
    public function haveParent(){
        if( $this->getParent()!==null) return true;
        return false;
    }
    public function haveChild(){
        if(count($this->_items)>0) return true;
        else{
            $this->_items = self::getChildListe($this->getId());
            if(count($this->_items)>0) return true;
        }
        return false;
    }
    
    /**
     * 
     * @return \modele_menu_item
     */
    public function getChild(){
        if($this->haveChild()){
            return $this->_items;
        }else{
            return array();
        }
    }
    public function getChildDatas($input=false){
        $retour = array();
        $child = $this->getChild();
        if(count($child)>0){
            foreach($child as $item){
                $retour[$item->getOrder()] = $item->getDatas($input);
            }
            ksort($retour);
        }
        return $retour;
    }
    public function getLabel($input=false){
        if($input) return $this->inputFormat($this->_label);
        else return $this->outputFormat($this->_label);
    }
    public function getTitle($input=false){
        if($input) return $this->inputFormat($this->_title);
        else return $this->outputFormat($this->_title);
    }
    public function getLink(){
        if($this->getModeleId()>0&&$this->getModele()!=''){
            eval('$target = new modele_'.$this->getModele().'('.$this->getModeleId().');');
            if(isset($target)){
                $this->_link = $target->getPermalien()->getLien();
            }
        }
        return $this->_link;
    }
    /**
     * renvoi l'url dans la langue indiquée
     * @param string $lang
     * @return string
     * @todo réécrire la requete de recherche du lien en multilangue
     */
    public function getTranslatedLink($lang=''){
        if($this->getModeleId()>0&&$this->getModele()!=''){
            eval('$target = new modele_'.$this->getModele().'('.$this->getModeleId().');');
            if(isset($target)){
                $this->_link = $target->getPermalien()->getTranslatedLien($lang);
            }
        }
        return $this->_link;
    }
    public function getModele(){
        return $this->_modele;
    }
    public function getModeleId(){
        return $this->_modele_id;
    }
    public function getTarget(){
        return $this->_target;
    }
    public function getUrl(){
        if($this->getModeleId()>0&&$this->getModele()!=''){
            eval('$target = new modele_'.$this->getModele().'('.$this->getModeleId().');');
            if(isset($target)){
                return $target->getUrl();
            }
        }
        return $this->getLink();
    }
    public function getTranslatedUrl($lang=''){
        if($this->getModeleId()>0&&$this->getModele()!=''){
            eval('$target = new modele_'.$this->getModele().'('.$this->getModeleId().');');
            if(isset($target)){
                return $target->getTranslatedUrl($lang);
            }
        }
        return $this->getTranslatedLink($lang);
    }
    
    public function getOrder(){
        return $this->_order;
    }
    public function getClass(){
        return $this->_class;
    }
    
    public function setDatas($datas){
        foreach($datas as $k=>$v){
            if($k == 'items' || $k == '_items'){
                /* destruction des sous menus supprimés */
                if($this->haveChild()){
                    foreach($this->getChild() as $orderOld=>$itemOld){     
                        if(!array_key_exists($orderOld, $v)){
                            $itemOld->delete();
                            unset($this->_items[$orderOld]);
                        }
                    }
                }
                if( count($v)>0 ){
                    foreach($v as $order=>$data){
                        if($data['label']!==''){
                            $newItem = new modele_menu_item($data['id']);
                            $newItem->setDatas($data);
                            $this->_items[$order] = $newItem;
                        }elseif(isset($this->_items[$order])){
                            $itemToDelete = $this->_items[$order];
                            $itemToDelete->delete();
                            unset($this->_items[$order]);
                        }
                    }
                }
            }else{
                if($k!='_id' && property_exists('modele_menu_item',$k)){
                    $this->$k = $v;
                }else{
                    $k = '_'.$k;
                    if($k!='_id' && property_exists('modele_menu_item',$k)){
                        $this->$k = $v;
                    }
                }
            }
        }
        return true;
    }
    public function getDatas($input=false) {
        $data = array();
        $data['id'] = $this->getId();
        $data['menu_id'] = $this->getMenuId();
        $data['label'] = $this->getLabel($input);
        $data['title'] = $this->getTitle($input);
        $data['link'] = $this->getLink();
        $data['modele'] = $this->getModele();
        $data['modele_id'] = $this->getModeleId();
        $data['url'] = $this->getUrl();
        $data['target'] = $this->getTarget();
        $data['order'] = $this->getOrder();
        $data['items'] = $this->getChildDatas($input);
        $data['class'] = $this->getClass();
        
        return $data;
    }
    
    public function save(){
        $sqlQueryItems = 'INSERT INTO '.self::getTable().' ';
        $sqlQueryItems .= '(`menu_id`,`menu_item_id`,`label`,`title`,`link`,`modele`,`modele_id`,`target`,`order`,`class`) ';
        $sqlQueryItems .= 'VALUES (';
        $sqlQueryItems .= $this->getMenuId().',';
        $sqlQueryItems .= $this->getParentId().',';
        $sqlQueryItems .= '"'.$this->getLabel(true).'",';
        $sqlQueryItems .= '"'.$this->getTitle(true).'",';
        $sqlQueryItems .= '"'.$this->getLink().'",';
        $sqlQueryItems .= '"'.$this->getModele().'",';
        $sqlQueryItems .= '"'.$this->getModeleId().'",';
        $sqlQueryItems .= '"'.$this->getTarget().'",';
        $sqlQueryItems .= $this->getOrder().',';
        $sqlQueryItems .= '"'.$this->getClass().'")';
        
        bdd_sql::doSql($sqlQueryItems,false);
        $this->_id = bdd_sql::getLastInsertId();
        
        return array('success'=>true,'datas'=>$this->getDatas());
    }
    
    public function update(){
        $sqlQuery = 'UPDATE '.self::getTable().' SET ';
        $sqlQuery .= '`label`="'.$this->getLabel(true).'", ';
        $sqlQuery .= '`menu_item_id`='.$this->getParentId().', ';
        $sqlQuery .= '`title`="'.$this->getTitle(true).'", ';
        $sqlQuery .= '`link`="'.$this->getLink().'", ';
        $sqlQuery .= '`modele`="'.$this->getModele().'", ';
        $sqlQuery .= '`modele_id`="'.$this->getModeleId().'", ';
        $sqlQuery .= '`target`="'.$this->getTarget().'", ';
        $sqlQuery .= '`order`='.$this->getOrder().', ';
        $sqlQuery .= '`class`="'.$this->getClass().'" ';
        $sqlQuery .= 'WHERE id='.$this->getId();
        bdd_sql::doSql($sqlQuery,false);
        
        if($this->haveChild()){
            foreach($this->getChild() as $child){
                if($child->getId()>0)$child->update();
                else $child->save();
            }
        }
        return array('success'=>true,'datas'=>$this->getDatas());
    }
    public function delete(){
        /*destruction sous menu*/
        if($this->haveChild()){
            foreach($this->getChild() as $child){
                $child->delete();
            }
        }
        $sqlQuery = 'DELETE FROM '.self::getTable().' WHERE id='.$this->_id.' LIMIT 1';
        bdd_sql::doSql($sqlQuery,false);
    }
    
    /* methodes statiques */
    /**
     * 
     * @return string
     */
    public static function getTable(){
        return PWE::getPrefixBdd().self::$_table;
    }
    
    /**
     * 
     * @param int $menu_id
     * @param int $start
     * @param int $limit
     * @return \modele_menu_item
     */
    public static function getListe($menu_id=0,$start = 0,$limit = 0){
        $sqlQuery = 'SELECT id FROM '.self::getTable();
        if($menu_id > 0){
            $sqlQuery .= ' WHERE menu_id='.$menu_id;
        }
        
        if($limit>0){
            $sqlQuery .=  ' LIMIT '.$start.', '.$limit;
        }
        
        $retour = array();
        $results = bdd_sql::doSql($sqlQuery,true);
        if($results['count']>0){
            foreach($results['results'] as $menuItem){
                $retour[] = new modele_menu_item($menuItem['id']);
            }
        }
        return $retour;
    }
    /**
     * 
     * @param int $menu_id
     * @param int $start
     * @param int $limit
     * @return \modele_menu_item
     */
    public static function getPrimaryListe($menu_id=0,$start = 0,$limit = 0){
        $sqlQuery = 'SELECT id FROM '.self::getTable().' WHERE menu_item_id IS NULL';
        if($menu_id > 0){
            $sqlQuery .= ' AND menu_id='.$menu_id;
        }
        
        if($limit>0){
            $sqlQuery .=  ' LIMIT '.$start.', '.$limit;
        }
        $retour = array();
        $results = bdd_sql::doSql($sqlQuery,true);
        if($results['count']>0){
            foreach($results['results'] as $menuItem){
                $retour[] = new modele_menu_item($menuItem['id']);
            }
        }
        return $retour;
    }
    
    /**
     * 
     * @param int $parent_id
     * @param int $start
     * @param int $limit
     * @return \modele_menu_item
     */
    public static function getChildListe($parent_id,$start = 0,$limit = 0){
        $sqlQuery = 'SELECT id,`order` FROM '.self::getTable().' WHERE menu_item_id='.$parent_id;
        $sqlQuery .=  ' ORDER BY `order`';
        if($limit>0){
            $sqlQuery .=  ' LIMIT '.$start.', '.$limit;
        }
        $retour = array();
        $results = bdd_sql::doSql($sqlQuery,true);
        if($results['count']>0){
            foreach($results['results'] as $menuItem){
                $retour[$menuItem['order']] = new modele_menu_item($menuItem['id']);
            }
        }
        return $retour;
    }
}
?>
